package com.yy.watchmen.service

import android.app.ActivityManager
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.IBinder
import android.os.Message
import android.util.Log
import com.yy.watchmen.ApkInstallReceiver
import com.yy.watchmen.AppUtils
import com.yy.watchmen.WatchmenFloatWindowManager
import com.yy.watchmen.utils.AdbUtils
import com.yy.watchmen.utils.FloatWindowPermissionUtils
import com.yy.watchmen.utils.WeakReferenceHandler

class WatchmenService : Service(), WeakReferenceHandler.IHandler {
    companion object {
//        const val WATCH_APP_PACKAGE_NAME = "com.yy.uu.voice.test"
        const val WATCH_APP_PACKAGE_NAME = "cn.com.smart.cabinet.device"
        private const val TAG = "WatchmenService"
    }

    override fun onBind(p0: Intent?): IBinder? {
        return null
    }

    private val mHandler = WeakReferenceHandler(this)

    override fun onCreate() {
        super.onCreate()
        registerReceiver(ApkInstallReceiver(), IntentFilter().apply {
            addAction(Intent.ACTION_PACKAGE_REMOVED)
            addAction(Intent.ACTION_PACKAGE_ADDED)
            addAction(Intent.ACTION_PACKAGE_REPLACED)
            addAction(Intent.ACTION_PACKAGE_CHANGED)
            addAction(Intent.ACTION_PACKAGE_INSTALL)
        })
        NotificationHelper.instance.apply {
            val notification = getNotification()
            notifyNotification(notification)
            startForeground(NotificationHelper.NOTIFICATION_ID, notification)
        }

        registerReceiver(TimeChangeReceiver(), IntentFilter().apply {
            addAction(Intent.ACTION_TIME_TICK)
        })

        mHandler.sendEmptyMessageDelayed(0, 5000)
    }

    override fun handleMessage(msg: Message) {
        checkLogic()
        mHandler.sendEmptyMessageDelayed(0, 3 * 1000)
    }

    private fun checkLogic() {
        if (!isAppRunning(this, WATCH_APP_PACKAGE_NAME)) {
            log("$WATCH_APP_PACKAGE_NAME 不在运行状态")
            AppUtils.launchApp(this, WATCH_APP_PACKAGE_NAME)
            val cmd = "adb shell am start -n ${WATCH_APP_PACKAGE_NAME}/${AppUtils.getLauncherActivity(this, WATCH_APP_PACKAGE_NAME)}"
            log("cmd命令：\n$cmd")
            AdbUtils.executeAdbCommand(cmd)
        } else {
            log("$WATCH_APP_PACKAGE_NAME 正在运行")
        }
    }

    /**
     * 检测某个应用是否正在运行
     */
    private fun isAppRunning(context: Context, packageName: String): Boolean {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val runningAppProcesses = activityManager.runningAppProcesses
        if (runningAppProcesses != null) {
            for (processInfo in runningAppProcesses) {
                if (processInfo.processName == packageName) {
                    return true
                }
            }
        }
        return false
    }

    /**
     * 系统时间改变的监听器
     */
    inner class TimeChangeReceiver : BroadcastReceiver() {

        override fun onReceive(context: Context, intent: Intent) {
            when (intent.action) {
                Intent.ACTION_TIME_TICK -> {
                    log("时间变啦")
                    checkLogic()
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mHandler.removeMessages(0)
    }

    private fun log(any: Any) {
        Log.d(TAG, "$any")
    }
}